package cn.anecansaitin.jep.interpreter.evaluators;

import cn.anecansaitin.jep.interpreter.Interpreter;
import cn.anecansaitin.jep.parser.ast.node.expression.Expression;
import cn.anecansaitin.jep.parser.ast.node.expression.Grouping;
import cn.anecansaitin.jep.parser.ast.node.expression.Ternary;
import cn.anecansaitin.jep.parser.ast.node.expression.literal.CharLiteral;

public class CharEvaluator {
    public static char evaluate(Expression expression) {
        return switch (expression) {
            case Ternary ternary -> ternary(ternary);
            case Grouping grouping -> evaluate(grouping.expression());
            case CharLiteral charLiteral -> charLiteral.value();
            default -> throw Interpreter.markError(expression, "未实现的运算符");
        };
    }

    private static char ternary(Ternary ternary) {
        boolean condition = BooleanEvaluator.evaluate(ternary.condition());
        Expression trueExpression = ternary.trueValue();
        Expression falseExpression = ternary.falseValue();

        if (condition) {
            return switch (trueExpression.resultType()) {
                case CHAR -> CharEvaluator.evaluate(trueExpression);
                default -> throw Interpreter.markError(ternary, "不支持的表达式结果类型");
            };
        } else {
            return switch (falseExpression.resultType()) {
                case CHAR -> CharEvaluator.evaluate(falseExpression);
                default -> throw Interpreter.markError(ternary, "不支持的表达式结果类型");
            };
        }
    }
}
